package com.dpiinc.TechPage.activity

import android.content.DialogInterface
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.view.MenuItemCompat
import androidx.lifecycle.Observer
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProviders
import androidx.paging.PagedList
import androidx.recyclerview.widget.RecyclerView
import cn.sharesdk.onekeyshare.OnekeyShare
import com.dpiinc.TechPage.*
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.adapter.NoteListAdapter
import com.dpiinc.TechPage.menu.MenuConnectActionProvider
import com.dpiinc.TechPage.pen.activity.ConnectPenActivity
import com.dpiinc.TechPage.pen.dialog.LowBatteryDialog
import com.dpiinc.TechPage.repository.Status
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import com.dpiinc.TechPage.room.bean.NoteEntity
import com.dpiinc.TechPage.user.setting.MyInfoActivity
import com.dpiinc.TechPage.user.utils.PermissionUtils
import com.dpiinc.TechPage.user.utils.ShareHelper
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.user.utils.ViewToBitmapUtil
import com.dpiinc.TechPage.viewmodel.EditNoteViewModel
import com.dpiinc.TechPage.viewmodel.NoteListViewModel
import com.dpiinc.TechPage.widget.BitmapUtils
import com.dpiinc.TechPage.widget.BitmapUtils.getOvalBitmap
import com.dpiinc.TechPage.widget.CommDialog
import com.dpiinc.TechPage.widget.LoadingView
import com.dpiinc.TechPage.widget.smartrefresh.api.RefreshLayout
import com.dpiinc.TechPage.widget.smartrefresh.listener.OnRefreshListener
import com.beiji.lib.pen.PenManager
import com.beiji.lib.pen.cache.PenCacheManager
import com.beiji.lib.pen.listener.OfflineDataListener
import com.beiji.lib.pen.model.DotUnit
import com.bumptech.glide.Glide
import com.hwangjr.rxbus.RxBus
import com.yanzhenjie.permission.Action
import com.yanzhenjie.recyclerview.*
import com.yanzhenjie.recyclerview.SwipeRecyclerView.RIGHT_DIRECTION
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration
import kotlinx.android.synthetic.main.activity_note_list.*
import java.io.ByteArrayInputStream

/**
 * 笔记列表
 * Created by X on 2018/6/29.
 *
 * 主界面  列表界面
 */
class NoteListActivity : BaseActivity() {
    @Suppress("unused")
    private val TAG = "NoteListActivity"

    private lateinit var model: NoteListViewModel
    private var connectActionProvider: MenuConnectActionProvider? = null
    private var viewModel: EditNoteViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_note_list)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        if (!checkUserValid()) {
            startActivity(Intent(this@NoteListActivity, LoginActivity::class.java))
            finish()
            return
        }
        PenCacheManager.instance.init(this, UserManager.getUserId())
        model = ViewModelProviders.of(this)[NoteListViewModel::class.java]
        showGuideDialog()

        checkWriteExternalStoragePermission()
        initView()
        model.loadNotes()
        addBatteryChangedCallback()
//        initUser()
        initAdapter()
        migrateData()
    }

    private fun migrateData() {
        DataMigrateHelper.migrate()
    }

    private fun initUser() {
        val db = RoomAiWriterDatabase.getInstance(this)
        val list = db.userDao().all
        if (list != null && list.size > 0) {
            val user = list[0]
            if (user.nickImage != null)
                showImage(user.nickImage)
        }
    }

    private fun showImage(nickImage: String) {
        if (TextUtils.isEmpty(nickImage)) {
            return
        }
        //利用Base64将字符串转换为ByteArrayInputStream
        val byteArray = Base64.decode(nickImage, Base64.DEFAULT)
        if (byteArray.size == 0) {
        } else {
            val byteArrayInputStream = ByteArrayInputStream(byteArray)

            //利用ByteArrayInputStream生成Bitmap
            val bitmap = BitmapFactory.decodeStream(byteArrayInputStream)
            toolbar.navigationIcon = BitmapDrawable(getResources(), getOvalBitmap(BitmapUtils.resizeBitmap(bitmap,
                    getResources().getDimension(R.dimen.dp30).toInt(), getResources().getDimension(R.dimen.dp30).toInt())))
        }
    }

    private fun addBatteryChangedCallback() {
        PenManager.instance.batteryChangedCallback = { percent ->
            if (PenManager.instance.isPenLowBattery()) {
                LowBatteryDialog.show(percent, this)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        PenManager.instance.registerDataCallback(penCallback)
        PenManager.instance.offlineDataCallback = offlineDataCallback
    }

    private val penCallback: (DotUnit) -> Boolean = {
        bringAppForeground()
        //把在新页面注册回调成功之前把点先缓存下来
        PenManager.instance.cacheDotTemporary(it)
        val intent = Intent(this@NoteListActivity, EditNoteActivity::class.java)
        startActivity(intent)
        false
    }

    private fun bringAppForeground() {
        if (AIWriteApplication.instance().isRunningForeground) {
            return
        }
        val intent = Intent(this, NoteListActivity::class.java)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        intent.action = Intent.ACTION_MAIN
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
        applicationContext.startActivity(intent)
    }

    private val offlineDataCallback = object : OfflineDataListener {
        override fun onOfflineDataCount(count: Int) {
            offline_data_tip_layout.visibility = if (count > 0) {
                View.VISIBLE
            } else {
                View.GONE
            }
        }

        override fun onOfflineDataDownloadProgress(progress: Int) {}
        override fun onOfflineDataReceive(dot: DotUnit) {}
        override fun onOfflineDataReceiveProgress(progress: Int) {}
    }

//    override fun onPause() {
//        super.onPause()
//        PenManager.instance.unRegisterDataCallback(penCallback)
//    }

    private fun checkUserValid(): Boolean {
        val db = RoomAiWriterDatabase.getInstance(this)
        val list = db.userDao().all
        return (list != null && list.size > 0)
    }

    private fun initView() {

//        list_note.setSwipeMenuCreator(swipeMenuCreator)
//        list_note.setSwipeMenuItemClickListener(mMenuItemClickListener)
        list_note.addItemDecoration(DefaultItemDecoration(getResources().getColor(android.R.color.transparent), ViewGroup.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.dp_8)))

        ptrl_container.setOnRefreshListener(object : OnRefreshListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                Log.i(TAG, "onRefresh: ")
                model.loadNotes()
//                Handler().postDelayed({
//                    ptrl_container.finishRefresh()
//                }, 2000)
            }

        })

        toolbar.setNavigationOnClickListener {
            startActivity(Intent(this@NoteListActivity, MyInfoActivity::class.java))
        }
        fab.setOnClickListener { _ ->
            startActivity(Intent(this@NoteListActivity, EditNoteActivity::class.java))
        }
        fab.setOnLongClickListener {
            if (AIWriteApplication.isDebug()) {
                startActivity(Intent(this, TestApiActivity::class.java))
            }
            true
        }
        offline_data_tip.setOnClickListener {
            offline_data_tip_layout.visibility = View.GONE
            startActivity(Intent(this, OfflineDataActivity::class.java))
        }
        btn_close_tip.setOnClickListener {
            offline_data_tip_layout.visibility = View.GONE
            PenManager.instance.removeOfflineData()
        }
        search_view.setOnClickListener {
            startActivity(Intent(this, SearchActivity::class.java))
        }
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private val swipeMenuCreator = object : SwipeMenuCreator {
        override fun onCreateMenu(swipeLeftMenu: SwipeMenu, swipeRightMenu: SwipeMenu, viewType: Int) {
            val width = getResources().getDimensionPixelSize(R.dimen.dp_90)

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            val height = ViewGroup.LayoutParams.MATCH_PARENT

            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            run {

                val shareItem = SwipeMenuItem(this@NoteListActivity)
                        .setBackground(R.color.color_f8f8f8)
                        .setImage(R.mipmap.ic_share)
                        .setText("")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height)
                swipeRightMenu.addMenuItem(shareItem) // 添加菜单到右侧。

                val deleteItem = SwipeMenuItem(this@NoteListActivity)
                        .setBackground(R.color.color_f8f8f8)
                        .setImage(R.mipmap.ic_delete)
                        .setText("")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height)
                swipeRightMenu.addMenuItem(deleteItem)// 添加菜单到右侧。

            }
        }
    }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private val mMenuItemClickListener = OnItemMenuClickListener { menuBridge, adapterPosition ->
        menuBridge.closeMenu()

        val direction = menuBridge.direction // 左侧还是右侧菜单。
        val menuPosition = menuBridge.position // 菜单在RecyclerView的Item中的Position。

        if (direction == RIGHT_DIRECTION) {
            //TODO 根据adapterPosition 删除对应数据
            if (menuPosition == 0) {
                //分享
                showShare()
            } else {
                //删除
                val builder = CommDialog.Builder()
                builder.setTitle(getString(R.string.delete_note_dialog_title))
                        .setMessage(getString(R.string.delete_note_dialog_message))
                        .setLeftButton(getString(R.string.delete_note_dialog_left_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                            dialogInterface.dismiss()
                        })
                        .setRightButton(getString(R.string.delete_note_dialog_right_button_text), DialogInterface.OnClickListener { dialogInterface, _ ->
                            dialogInterface.dismiss()
                        })
                        .setRightButtonTextColor(ContextCompat.getColor(this, R.color.comm_dialog_btn_text_color_important))
                builder.build().show(supportFragmentManager)
            }
        }
    }

    private fun initAdapter() {
        val glide = Glide.with(this)
        val adapter = NoteListAdapter(this, glide) {
            model.retry()
        }
        list_note.adapter = adapter
        adapter.registerAdapterDataObserver(observer)
        model.notes.observe(this, Observer<PagedList<NoteEntity>> {
            empty_view.visibility = if (it == null || it.isEmpty()) {
                View.VISIBLE
            } else {
                View.GONE
            }
            adapter.submitList(it)
            ptrl_container.finishRefresh()
            model.saveAll()//TODO
        })
        model.networkState.observe(this, Observer {
            it ?: return@Observer
            toastIfDebug(it.toString())
            AWLog.e(EditNoteActivity.TAG, it.toString())
            when (it.status) {
                Status.SUCCESS -> {
                    adapter.setNetworkState(it)
                    model.retry()
                    adapter.notifyDataSetChanged()
                }
                else -> {
                }
            }
        })

        adapter!!.setOnSwipeListener(object : NoteListAdapter.onSwipeListener {
            override fun onClickShare(pos: Int, note: NoteEntity) {
//                toast("分享"+pos)
                Log.i(TAG, "onClickShare: ")
                viewModel = EditNoteViewModel(note, application)
                stroke_view.clear()
//                viewModel = ViewModelProviders.of(this@NoteListActivity, object : ViewModelProvider.Factory {
//                    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
//                        @Suppress("UNCHECKED_CAST")
//                        return EditNoteViewModel(note, application) as T
//                    }
//                })[EditNoteViewModel::class.java]
                viewModel!!.needRedraw = false
                bindView()
                viewModel!!.downloadFilesIfNotExists()
            }

            override fun onClickDelete(pos: Int) {
//                toast("删除"+pos)
                ToastUtils.showCenterTip(this@NoteListActivity, getString(R.string.toast_edit_note_delete_success))
            }
        })
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_note_list, menu)
        val connectMenu = menu?.findItem(R.id.menu_connect)
                ?: return super.onPrepareOptionsMenu(menu)
        connectActionProvider = MenuItemCompat.getActionProvider(connectMenu) as MenuConnectActionProvider
        RxBus.get().register(connectActionProvider)
        return super.onCreateOptionsMenu(menu)
    }

    private fun showShare() {
        val oks = OnekeyShare()
        //关闭sso授权
        oks.disableSSOWhenAuthorize()

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(getString(R.string.app_name))
        // titleUrl QQ和QQ空间跳转链接
       // oks.setTitleUrl("http://sharesdk.cn")
        // text是分享文本，所有平台都需要这个字段
        oks.text = "我是分享文本"
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg")//确保SDcard下面存在此张图片
        // url在微信、微博，Facebook等平台中使用
      //  oks.setUrl("http://sharesdk.cn")
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment("我是测试评论文本")
        // 启动分享GUI
        oks.show(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        connectActionProvider?.let {
            RxBus.get().unregister(it)
        }
    }

    private fun showGuideDialog() {
        if (AIWriteSettings.isNewUserGuideShowed()) {
            return
        }
        AIWriteSettings.setNewUserGuideShowed(true)
        val view = View.inflate(this, R.layout.new_user_guide_dialog_layout, null)
        val btnConnect = view.findViewById<TextView>(R.id.btn_go_connect)
        val btnClose = view.findViewById<ImageView>(R.id.btn_close)
        val newUserGuideDialog = AlertDialog.Builder(this)
                .setView(view)
                .create()
        btnConnect.setOnClickListener {
            val connectPenIntent = Intent(this, ConnectPenActivity::class.java)
            connectPenIntent.putExtra(ConnectPenActivity.PARAM_FROM, ConnectPenActivity.FROM_NOTE_LIST)
            startActivity(connectPenIntent)
            newUserGuideDialog.dismiss()
        }
        btnClose.setOnClickListener { newUserGuideDialog.dismiss() }
        newUserGuideDialog.show()
    }

    private val observer = object : RecyclerView.AdapterDataObserver() {
        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            if (positionStart == 0) {
                list_note.smoothScrollToPosition(0)
            }
        }
    }

    private fun checkWriteExternalStoragePermission() {
        val granted = Action<List<String>> {}
        val denied = Action<List<String>> {
//            ToastUtils.showTopTip(this@NoteListActivity, getString(R.string.no_authority_use))
        }
        if (PermissionUtils.checkWRITE_EXTERNAL_STORAGE(this@NoteListActivity, granted, denied)) {
        }
    }

    fun bindView() {
        viewModel!!.downloadState.observe(this, Observer {
            it ?: return@Observer
            when (it.status) {
                Status.SUCCESS -> {
//                    LoadingView.dismissLoadingView()
                    startCache()
                }
                Status.RUNNING -> {
//                    LoadingView.dismissLoadingView()
//                    LoadingView.createLoadingViewAndShow(this, 0, it.msg)
                }
                Status.FAILED -> {
                    //TODO 这里要区分什么文件下载失败，如果是笔迹文件下载失败，才不需要重绘..

                    viewModel!!.needRedraw = false
                    ToastUtils.showCenterTip(this, getString(R.string.toast_download_files_failed))
//                    LoadingView.dismissLoadingView()
                    startCache()
                }
            }
        })
    }

    private fun startCache() {
        stroke_view.startCache(viewModel!!.note.noteId)
        if (viewModel!!.needRedraw) {
            LoadingView.createLoadingViewAndShow(this, 0, null)
            //TODO Yang
//            stroke_view.drawStrokeFromCacheFile(true) {
            stroke_view.drawStrokeFromCacheFile {
                stroke_view.endCache()
                LoadingView.dismissLoadingView()
                handlerShareClick(viewModel!!.note)
            }
        } else
            handlerShareClick(viewModel!!.note)
    }

    private fun handlerShareClick(it: NoteEntity) {
        val bitmapPathList: ArrayList<String> = PenCacheManager.instance.getPenStrokeBitmapPathList(it.noteId)
        if (bitmapPathList.size == 0) {
            ToastUtils.showTopTip(this, getString(R.string.toast_replay_empty_stroke))
            LoadingView.dismissLoadingView()
            return
        }
        setModifyTimeForShare(it)
        ViewToBitmapUtil.generateAllBitmap(this, bitmapPathList)
        checkPermissionShowDialog(bitmapPathList)
    }

    private fun setModifyTimeForShare(it: NoteEntity) {
        ViewToBitmapUtil.setShareTime(it.modifyTime);
        ViewToBitmapUtil.setShareTitle(it.noteName)
    }

    private fun checkPermissionShowDialog(bitmapPathList: ArrayList<String>) {

        val granted = Action<List<String>> {
            ShareHelper.showShareDialog(this, bitmapPathList,"")
        }
        val denied = Action<List<String>> {
            ToastUtils.showTopTip(this, getString(R.string.no_authority_share))
            Log.d(EditNoteActivity.TAG, "onAction denied")
        }
     //   if (PermissionUtils.checkWRITE_EXTERNAL_STORAGE(this, granted, denied)) {
            ShareHelper.showShareDialog(this, bitmapPathList,"")
     //   }

    }
}
